package net.lgy.controller;


import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import net.lgy.config.MinioConfig;
import net.lgy.util.CommonUtil;
import net.lgy.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@RestController
@Slf4j
@RequestMapping("/api/test/v1")
public class testController {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioConfig minioConfig;

    @PostMapping("/upload")
    public JsonData testUpload(@RequestParam("file")MultipartFile file){
        log.info("开始上传文件");
        String OriginalFilename = CommonUtil.getFilePath(file.getOriginalFilename());
//        读取文件流上传到miniIO
        try {
            InputStream inputStream = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(OriginalFilename).stream(inputStream, inputStream.available(), -1)
                    .contentType(file.getContentType()).build());


        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + OriginalFilename;
        return JsonData.buildSuccess(url);

    }




}
